import React, { useRef, useState, useEffect } from 'react'
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { PlusOutlined, EllipsisOutlined, PayCircleOutlined } from '@ant-design/icons'
import { Table, Tag, Space, Button, Dropdown, tags, Modal, Form, Input, Select, DatePicker, Upload, message, Image, Row, Col, InputNumber, Statistic, Popconfirm } from 'antd';
import request from '@/utils/request';
import moment from 'moment';
const { Option } = Select
const { TextArea } = Input;
const layoutShort = {
    labelCol: { span: 6 },
    wrapperCol: { span: 10 }
}
const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 }
}
const Test = () => {
    const [houseList, setHouseList] = useState()
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [isModalVisibleForPay, setIsModalVisibleForPay] = useState(false)
    const [selectVal, setSelectVal] = useState('1')  //选择的月数
    const [param, setParam] = useState()  //结算时需要的参数
    const [electricity, setElectricity] = useState(0) //消耗电数
    // const [money,setMoney] = useState(333) //最后的金额
    const [img, setImg] = useState()
    const actionRef = useRef()
    const [form] = Form.useForm(); // 利用Form引入也可
    useEffect(async () => {
        const res = await request('/api/tablelist/house/')
        setHouseList(res)
    }, [isModalVisible])

    const columns = [
        {
            title: '房屋名称',
            dataIndex: 'house_name',
            key: 'house_name',
            align: 'center',
            width: 100
        },
        {
            title: '房屋状态',
            dataIndex: 'status',
            key: 'status',
            width: 75,
            align: 'center',
            valueEnum: {
                1: { text: '在住', status: 'success' },
                0: { text: '空置', status: 'Error' },

            },
        },
        {
            title: '缴费天数',
            align: 'center',
            width: 100,
            render: (_, recode) => {
                const nowAday = moment(new Date().toLocaleDateString()).format('YYYY-MM-DD')
                // console.log(nowAday)
                // console.log(recode.last_pay_day)
                let differ
                if (recode.last_pay_date === null) {
                    differ = null
                } else {

                    differ = moment(recode.last_pay_date).diff(moment(nowAday), 'days') || 0;
                }
                // const differ = moment("2019-02-01").diff(moment("2019-01-01"),'days');
                let node
                if (differ == null) {
                    return <div>-</div>
                }
                if (differ > 0) {
                    node = <div style={{ color: '#73d13d' }}>{differ}天</div>
                } else if (differ == 0) {
                    node = <div style={{ color: '#ffa940' }}>该缴费了</div>
                } else {
                    if (differ > -30) {
                        node = <div style={{ color: '#f5222d' }}>逾期{Math.abs(differ)}天</div>
                    } else {
                        const month = Math.abs(Math.floor(differ / 30))
                        const day = Math.abs(differ % 30)
                        node = <div style={{ color: '#f5222d' }}>逾期{month}月{day}天</div>
                    }
                }
                return node
            }
        },
        {
            title: "电底",
            dataIndex: 'electricity',
            align: 'center',
            width: 100
        },
        {
            title: '租客',
            dataIndex: 'name',
            align: 'center',
            key: 'name',
            width: 100
        },
        {
            title: '电话',
            key: 'phone',
            dataIndex: 'phone',
            align: 'center',
            width: 200
        },
        {
            title: '房租（元/月)',
            dataIndex: 'house_price',
            align: 'center',
            width: 150
        },
        {
            title: '水费（元/月）',
            dataIndex: 'water_price',
            align: 'center',
            width: 150
        },
        {
            title: '身份证',
            dataIndex: 'id_card_forward',
            align: 'center',
            width: 75,
            render: (_, recode) => {
                const node = recode.id_card_forward === null ? <div>-</div> : <Image width={50} src={recode.id_card_forward} />
                return (
                    node
                )
            }
        },
        {
            title: '入住日期',
            dataIndex: 'in_date',
            align: 'center',
            width: 100
        },
        {
            title: '上次结算日期',
            dataIndex: 'last_pay_date',
            align: 'center',
            width: 100
        },
        {
            title: '备注',
            dataIndex: 'remark',
            align: 'center',
            ellipsis: true,
            width: 200
        },
        {
            title: '操作',
            align: 'center',
            fixed: 'right',
            render: (text, record, _, action) => [
                <Space size='large'>
                    <a key="clear" disabled={record.status == 0 ? true : false} onClick={() => {
                        setIsModalVisibleForPay(true)
                        const param = {
                            electricity: record.electricity,
                            house_price: record.house_price,
                            water_price: record.water_price,
                            last_pay_date: record.last_pay_date,
                            people_id: record.people_id,
                            remark: record.remark
                        }
                        setSelectVal('1')
                        setElectricity(0)
                        setParam(param)
                    }}
                    >
                        结算
                    </a>
                    <a key="goOut" disabled={record.status == 0 ? true : false}>
                        <Popconfirm
                            // title={record.last_pay_date}
                            title={moment(record.last_pay_date).diff(moment(new Date()), 'days') >= 0 ? '确定该用户要搬出吗' : '该用户尚在欠费，已经跑路了吗'}
                            onConfirm={async () => {
                                const hide = message.loading('正在搬出用户', 0);
                                const res = await request(`/api/tablelist/${record.people_id}/`, { method: 'DELETE' })
                                if (res?.status == 200) {
                                    hide()
                                    message.success('新租户搬出成功');
                                    actionRef.current.reloadAndRest()
                                }else{
                                    hide()
                                    message.warn('新租户搬出失败');
                                }
                            }}
                            okText="是的"
                            cancelText="算了"
                        >
                            搬出
                        </Popconfirm>
                    </a>
                </Space>
            ],
        }

    ];

    const handleCreate = () => {
        setIsModalVisible(true)
    }

    const handleOk = async (value) => {
        const res = await form.validateFields()
        const hide = message.loading('正在创建用户', 0);
        const date = moment(res.in_date).format('YYYY-MM-DD');
        const { address } = res
        const newAddress = address.province + address.city + address.area
        const param = {
            ...res,
            address: newAddress,
            in_date: date,
            picture: img
        }
        const forms = new FormData();
        for (let key in param) {
            forms.append([key], param[key])
        }

        const response = await request('/api/tablelist/', { method: 'post', data: forms })
        hide()
        if (response?.status == '200') {
            message.success('新租户添加成功');
            form.resetFields()
            setIsModalVisible(false)
            actionRef.current.reloadAndRest()
        } else {
            message.success('新租户添加失败');
        }

    }

    const handleElectricChange = (value) => {
        const electricity = value - param.electricity
        setElectricity(electricity)
    }

    const handleOkForPay = async () => {
        const { people_id, house_price, water_price, remark } = param
        const hide = message.loading('正在结算', 0);
        const params = {
            pay_to_date: moment(param.last_pay_date).add(selectVal, 'M').format('YYYY-MM-DD'),
            pay_date: moment(new Date().toLocaleDateString()).format('YYYY-MM-DD'),
            people_id,
            house_price: house_price * selectVal,
            water_price: water_price * selectVal,
            electricity_price: electricity * 1.5,
            all_price: selectVal * (house_price + water_price) + electricity * 1.5,
            remark,
        }
        const res = await request('/api/tablelist/', { method: 'put', data: params })
        hide()
        if (res?.status == '200') {
            message.success('结算成功');
            setIsModalVisibleForPay(false)
            actionRef.current.reloadAndRest()
        } else {
            message.success('结算失败');
        }
    }
    return (
        <div>
            <ProTable
                columns={columns}
                actionRef={actionRef}
                request={
                    async (params = {}, sort, filter) => {

                        const res = await request('/api/tablelist/', {
                            params,
                        });
                        res.data?.forEach(e => {
                            if (e.status == null) {
                                e.status = 0
                            }
                        })
                        return res
                    }}
                rowKey="id"
                scroll={{ x: 1500 }}
                search={false}
                pagination={{
                    pageSize: 20,
                }}
                dateFormatter="string"
                headerTitle="租房人员管理"
                toolBarRender={() => [
                    <Button key="button" icon={<PlusOutlined />} type="primary" onClick={handleCreate}>
                        新建
                    </Button>,

                ]} />
            <Modal title="新增租户" visible={isModalVisible} onOk={handleOk} onCancel={() => setIsModalVisible(false)}>
                <Form
                    name="rend_people"
                    form={form}
                    {...layoutShort}
                >
                    <Form.Item
                        label="入住房屋"
                        name="house_id"
                        rules={[{ required: true, message: '请选择入住的房屋' }]}
                    >
                        <Select  >
                            {Array.isArray(houseList) ? houseList?.map((item) => <Option key={item.key} value={item.value}>{item.label}</Option>) : ''}
                        </Select>
                    </Form.Item>

                    <Form.Item
                        label="住户名称"
                        name="name"
                        rules={[{ required: true, message: '请输入住户的名称' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="联系方式"
                        name="phone"
                        rules={[{ required: true, message: '请输入住户的联系方式' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="地址"
                        {...layout}
                    >
                        <Input.Group compact>
                            <Form.Item
                                name={['address', 'province']}
                                noStyle
                                rules={[{ required: true, message: '请输入省份' }]}
                            >
                                <Input style={{ width: '30%' }} />
                            </Form.Item>
                            <span style={{ lineHeight: '32px', padding: '0 5px 0 5px' }}>•</span>
                            <Form.Item
                                name={['address', 'city']}
                                noStyle
                                rules={[{ required: true, message: '请输入城市' }]}
                            >
                                <Input style={{ width: '30%' }} />
                            </Form.Item>
                            <span style={{ lineHeight: '32px', padding: '0 5px 0 5px' }}>•</span>
                            <Form.Item
                                name={['address', 'area']}
                                noStyle
                                rules={[{ required: true, message: '请输入区/县' }]}
                            >
                                <Input style={{ width: '30%' }} />
                            </Form.Item>
                        </Input.Group>
                    </Form.Item>
                    <Form.Item
                        {...layout}
                        style={{ width: 'calc(40% - 4px)', display: 'inline-flex', marginLeft: '66px' }}
                        name='house_price'
                        label='房租'
                        rules={[{ required: true, message: '请输入房租' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        {...layout}
                        style={{ width: 'calc(40% - 4px)', display: 'inline-flex' }}
                        name='water_price'
                        label='水费'
                        rules={[{ required: true, message: '请输入水费' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name='in_date'
                        label='入住日期'
                        rules={[{ required: true, message: '请输入入住日期' }]}
                    >
                        <DatePicker style={{ width: '100%' }} />
                    </Form.Item>
                    <Form.Item
                        label="身份证正面"
                        name="picture"
                        valuePropName="file"
                        extra="请选择图片进行上传"
                        rules={[{ required: true, message: '请上传身份证正面图' }]}
                    >
                        <Upload listType="picture" maxCount={1} listType='picture-card' beforeUpload={file => setImg(file)}>
                            点击进行上传
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        label="备注"
                        name="remark"
                    >
                        <TextArea rows={4} />
                    </Form.Item>
                </Form>
            </Modal>
            {isModalVisibleForPay && <Modal title="结算菜单" okText='已收款' visible={isModalVisibleForPay} onOk={handleOkForPay} onCancel={() => setIsModalVisibleForPay(false)}>
                <Row gutter={12}>
                    <Col span={4}>
                    </Col>
                    <Col span={4}>
                        结算到：
                    </Col>
                    <Col span={12}>
                        <Select
                            style={{ width: '200px' }}
                            value={selectVal}
                            onChange={(e) => {
                                setSelectVal(e)
                            }}>
                            <Option key='1' value='1'>一月后</Option>
                            <Option key='1' value='2'>二月后</Option>
                            <Option key='1' value='3'>三月后</Option>
                            <Option key='1' value='4'>四月后</Option>
                            <Option key='1' value='5'>五月后</Option>
                            <Option key='1' value='6'>半年后</Option>
                        </Select>
                    </Col>
                </Row>
                <Row gutter={12} style={{ marginTop: "15px" }}>
                    <Col span={3}>
                    </Col>
                    <Col span={5}>
                        &nbsp;新的电底：
                    </Col>
                    <Col span={12}>
                        <InputNumber style={{ width: '200px' }} min={param.electricity} defaultValue={param.electricity} onChange={handleElectricChange} />
                    </Col>
                </Row>
                <Row gutter={12} style={{ marginTop: "15px" }}>
                    <Col span={4}>
                    </Col>
                    <Col span={4}>
                        &nbsp;&nbsp;备注：
                    </Col>
                    <Col span={12}>
                        <TextArea rows={4} value={param.remark} onChange={
                            ({ target: { value } }) => {
                                let a = { ...param }
                                a = {
                                    ...a,
                                    remark: value
                                }
                                setParam(a)
                            }
                        } />
                    </Col>
                </Row>
                <div style={{ display: 'flex', justifyContent: 'center', marginTop: '30px' }}>
                    (租金：{param.house_price} * {selectVal} + 水费：{param.water_price} * {selectVal} + 电费：1.5 * {electricity} = {selectVal * (param.house_price + param.water_price) + 1.5 * electricity})
                </div>
                <div style={{ display: 'flex', justifyContent: 'center', marginTop: '30px' }}>
                    <Statistic title="&nbsp;&nbsp;&nbsp;&nbsp;需缴纳(元)" value={selectVal * (param.house_price + param.water_price) + 1.5 * electricity} precision={2} prefix='￥' />
                </div>
            </Modal>}
        </div >
    )
}
export default Test